<template>
    <view :class="uiStyle == 1 ? '' : 'uiStyle'">
        <topBar text="消息"></topBar>
        <view class="clearAll" @tap="clearAll" v-if="messageList && messageList.length > 0">清除未读</view>
        <view class="message-block" v-if="messageList && messageList.length > 0">
            <view
                class="message-item"
                @tap="goPage"
                :data-id="item.id"
                :data-url="'../socks/socks?manageId=' + (item.manageId ? item.manageId : '') + '&otherName=' + item.name + '&id=' + (item.id ? item.id : '')"
                :data-type="item.messageType"
                :data-record="item.reserveRecordId"
                :data-system="item.systemId"
                v-for="(item, index) in messageList"
                :key="index"
            >
                <!-- <image wx:if="{{icons[item.messageType]}}" src="{{icons[item.messageType]}}" mode="widthFix"></image>
    <image wx:else src="/assets/img/message/default.png" mode="widthFix"></image> -->

                <image style="position: relative" :src="item.headImageUrl ? item.headImageUrl : '../../static/assets/img/person.png'">
                    <view v-if="item.senderIdentityId != identityId && item.contentState == -1" class="redCircle"></view>
                </image>

                <!-- <view class="{{item.messageState==1?'red':'white'}}"></view> -->

                <view class="message-item-info">
                    <view class="message-item-info-title">
                        <text>{{ item.name }}</text>
                        <view class="message-item-right">{{ item.createTime }}</view>
                    </view>
                    <view class="message-item-info-content">{{ item.content ? item.content : '[图片]' }}</view>
                </view>
            </view>
        </view>
        <view v-else>
            <noData text="暂无聊天消息" />
        </view>
    </view>
</template>

<script>
import noData from '@/pages/components/noData/noData';
import api from './../../utils/api.js';
import util from './../../utils/util.js';
import websocket from './../../utils/websocket.js';
export default {
    components: {
        noData
    },
    data() {
        return {
            pageNumber: 1,
            activeIndex: 0,

            //0:系统消息  1互动消息
            searchParams: {
                token: uni.getStorageSync('AUTHORIZATION'),
                indentityId: '' //wx.getStorageSync("identityId")
                // messageClassifyType: "8",
            },

            icons: {
                22: '../../static/assets/img/message/announce.png',
                23: '../../static/assets/img/message/family.png',	
                26: '../../static/assets/img/message/system.png',
                28: '../../static/assets/img/message/question.png',
                27: '../../static/assets/img/message/report.png',
                29: '../../static/assets/img/message/default.png',
                30: '../../static/assets/img/message/vistor.png',
                31: '../../static/assets/img/message/volunteer.png',
                32: '../../static/assets/img/message/volunteer.png',
                33: '../../static/assets/img/message/volunteer.png',
                34: '../../static/assets/img/message/wish.png',
                35: '../../static/assets/img/message/party.png',
                36: '../../static/assets/img/message/discuss.png',
                37: '../../static/assets/img/message/fee.png',
                38: '../../static/assets/img/message/maintain.png',
                40: '../../static/assets/img/message/office.png',
                41: '../../static/assets/img/message/office.png',
                42: '../../static/assets/img/message/office.png',
                43: '../../static/assets/img/message/message1.png',
                44: '../../static/assets/img/message/message3.png',
                45: '../../static/assets/img/message/message2.png',
                46: '../../static/assets/img/message/message4.png',
                50: '../../static/assets/img/message/jifen.png'
            },

            messageList: [
                {
                    type: 22,
                    messageTypeName: '志愿者服务',
                    message: '志愿者申请审批已通过。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 2,
                    messageTypeName: '报事报修',
                    message: '您的上报时间状态有更新，请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 3,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 4,
                    messageTypeName: '宠物登记',
                    message: '您的宠物疫苗接种时间，已经到期，请尽快安排时间打疫苗。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 3,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 23,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                }
            ],

            messageList: [],

            messageListBf: [
                {
                    type: 1,
                    messageTypeName: '志愿者服务',
                    message: '志愿者申请审批已通过。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 2,
                    messageTypeName: '报事报修',
                    message: '您的上报时间状态有更新，请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 3,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 4,
                    messageTypeName: '宠物登记',
                    message: '您的宠物疫苗接种时间，已经到期，请尽快安排时间打疫苗。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 3,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 23,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 23,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 23,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 23,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 23,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 23,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 23,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 23,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 23,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                },
                {
                    type: 23,
                    messageTypeName: '微心愿',
                    message: '有一条微心愿申请结果请查看。',
                    time: '2021-05-31 19:10'
                }
            ],

            identityId: '',
            name: '',
			uiStyle:1
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
		this.uiStyle = uni.getStorageSync('uiStyle')
        const identityId = uni.getStorageSync('identityId');
        const name = uni.getStorageSync('name');
        this.setData({
            identityId: identityId,
            name: name
        });
        var that = this; //socket链接

        websocket.connect('?token=' + uni.getStorageSync('AUTHORIZATION'), function (res) {
            console.log('socket推送成功:' + res);
            that.getData();
            that.isWaitingToRead();
        });
        this.getData();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this;
        const identityId = uni.getStorageSync('identityId');
        this.setData({
            identityId: identityId
        });
        websocket.connect('?token=' + uni.getStorageSync('AUTHORIZATION'), function (res) {
            console.log('socket推送成功:' + res);
            that.getData();
            that.isWaitingToRead();
        });
        this.getData();
        this.isWaitingToRead();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.isWaitingToRead();
        uni.closeSocket();
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        uni.closeSocket();
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage: function () {},
    //监听用户下拉动作
    onPullDownRefresh(e) {
        console.log('监听用户下拉动作');
        let num = this.pageNumber + 1;
        this.setData(
            {
                pageNumber: num
            },
            () => this.getData()
        );
    },
    onReachBottom(e) {
        console.log('上拉刷新');
    },
    methods: {
        isWaitingToRead() {
            //新消息留言
            const unionId = uni.getStorageSync('unionId');

            if (!unionId) {
                return;
            }

            util.request(
                api.isWaitingToRead,
                {
                    unionId: unionId
                },
                'POST',
                'application/x-www-form-urlencoded'
            ).then((res) => {
                console.log(res);

                if (res.data) {
                    uni.showTabBarRedDot({
                        index: 1
                    });
                } else {
                    uni.hideTabBarRedDot({
                        index: 1
                    });
                }
            });
        },

        clearAll() {
            var that = this;
            console.log('清除消息');
            uni.showLoading({
                title: '加载中'
            });
            util.request(api.allRead + '?unionId=' + uni.getStorageSync('unionId'), 'get')
                .then((res) => {
                    uni.hideLoading();

                    if (res.code == 0) {
                        uni.showToast({
                            title: '清除成功！',
                            icon: 'none'
                        });
                        that.isWaitingToRead();
                        that.getData(); // Toast('清除成功！')
                    } else {
                        uni.showToast({
                            title: res.msg || '接口出错了，请稍后再试',
                            icon: 'none'
                        });
                    }
                })
                .catch((err) => {
                    uni.hideLoading();
                    uni.showToast({
                        title: err || '接口出错了，请稍后再试',
                        icon: 'none'
                    });
                });
        },

        getData() {
            var that = this;
            console.log('getData'); // wx.showLoading({
            //   title: '加载中',
            // })

            util.request(api.findAllMessage + '?unionId=' + uni.getStorageSync('unionId') + '&pageNumber=1&pageSize=' + 10 * this.pageNumber, 'get')
                .then((res) => {
                    uni.hideLoading();

                    if (res.success) {
                        for (var i = 0; i < res.data.content.length; i++) {
                            if (res.data.content[i].senderIdentityId != uni.getStorageSync('identityId')) {
                                res.data.content[i].name = res.data.content[i].senderNickname;

                                if (res.data.content[i].headImageUrl) {
                                    res.data.content[i].headImageUrl = res.data.content[i].headImageUrl;
                                } else {
                                    res.data.content[i].headImageUrl = '';
                                }
                            }

                            if (res.data.content[i].recipientUserId != uni.getStorageSync('identityId')) {
                                res.data.content[i].name = res.data.content[i].recipientNickname;

                                if (res.data.content[i].recipientHeadImageUrl) {
                                    res.data.content[i].headImageUrl = res.data.content[i].recipientHeadImageUrl;
                                } else {
                                    res.data.content[i].headImageUrl = '';
                                }
                            } // if (res.data.content[i].headImageUrl) {
                            //   (function (i,img){
                            //     util.request(api.getEncryPath + "?path=" + img, "", "POST")
                            //     .then(res => {
                            //       console.log(res)
                            //       that.data.messageList[i].headImageUrl = res;
                            //       that.setData({
                            //         messageList: that.data.messageList
                            //       });
                            //     })
                            //     })(i,res.data.content[i].headImageUrl);
                            // }
                        }

                        this.setData({
                            messageList: res.data.content
                        });
                    } else {
                        Toast(res.msg || '接口出错了，请稍后再试');
                    }
                })
                .catch((err) => {
                    uni.hideLoading();
                    uni.showToast({
                        title: err || '接口出错了，请稍后再试',
                        icon: 'none'
                    });
                });
        },

        mark(event) {
            let param = {
                token: uni.getStorageSync('AUTHORIZATION'),
                // indentityId: 790,//wx.getStorageSync("identityId")
                messageType: event.currentTarget.dataset.type,
                systemId: event.currentTarget.dataset.system
            };
        },

        goPage(event) {
            console.log(event);
            let type = event.currentTarget.dataset.type;
            let url = event.currentTarget.dataset.url;
            this.changeMessageState(event);

            if (url) {
                uni.navigateTo({
                    url
                });
            } else {
                this.getData();
            }
        },

        /**
         * 切换Tab
         */
        changeTab(event) {
            let index = event.currentTarget.dataset.index;
            this.setData({
                activeIndex: index || 0 // messageList:index==0?this.data.messageListBf:[]
            });
            this.getData();
        },

        changeMessageState(event) {
            let { id, recipientUserId } = event.currentTarget.dataset;
            util.request(api.messageRead + '?messageId=' + id + '&recipientUserId=' + uni.getStorageSync('identityId'), 'get')
                .then((res) => {})
                .catch((err) => {});
        }
    }
};
</script>
<style>
@import './message.css';
</style>
